<?php
class Turn extends AppModel {
	var $name = 'Turn';
	var $validate = array(
		'user_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);
	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $belongsTo = array(
		'Client' => array(
			'className' => 'Client',
			'foreignKey' => 'client_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Person' => array(
			'className' => 'Person',
			'foreignKey' => 'person_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Stateturn' => array(
			'className' => 'Stateturn',
			'foreignKey' => 'stateturn_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Staterecord' => array(
			'className' => 'Staterecord',
			'foreignKey' => 'staterecord_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Product' => array(
			'className' => 'Product',
			'foreignKey' => 'producto_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'user_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Doctor' => array(
			'className' => 'User',
			'foreignKey' => 'doctor_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Agenda' => array(
			'className' => 'Agenda',
			'foreignKey' => 'agenda_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);


	function ObtenerTurnos($jDataTurn) {
		//-----------------------------------------------------------------------
		//                                                       Json de Entrada:
		//	$DataTurn['client_id']       = $client_id;
		//	$DataTurn['user_id']         = $user_id;
		//	$DataTurn['profesional_id']  = $profesional_id;
		//	$DataTurn['sucursal_id']     = $sucursal_id;
		//	$DataTurn['rol_actual']      = $rol_actual;
		//	$DataTurn['agenda_id']       = $agenda_id;
		//	$DataTurn['fecha_inicio']    = $fecha_inicio;
		//	$DataTurn['fecha_fin']       = $fecha_fin;
		//	$DataTurn['client_timezone'] = $_SESSION['Client']['timezone'];
		//-----------------------------------------------------------------------	


		$DataTurn = json_decode($jDataTurn, true);

		$client_tz = new DateTimeZone($DataTurn['client_timezone']);
		$date      = new DateTime();
		$date->setTimezone($client_tz);

		//--- Formatea y valida las fechas
		$fecha_inicio    = !empty($DataTurn['fecha_inicio']) ? $DataTurn['fecha_inicio'] : date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")) );
		$fecha_fin       = !empty($DataTurn['fecha_fin'])    ? $DataTurn['fecha_fin']    : date("Y-m-d", mktime(23,59,59,date("m"),date("d"),date("Y")) );
		$tz_fecha_inicio =  $date->format($fecha_inicio);				
		$tz_fecha_fin    =  $date->format($fecha_fin);

		$agenda_id   = $DataTurn['agenda_id']>0 ? $DataTurn['agenda_id'] : 0 ;
		$client_id   = $DataTurn['client_id']>0 ? $DataTurn['client_id'] : 0 ;
		$sucursal_id = $DataTurn['sucursal_id'] ;


		App::import('PeopleProduct','Agenda');


		if(!$agenda_id){

			//------------------------------------------------------------
			// Si no esta definida la Agenda, muestro los Turnos de Todos
			//                        Obtengo las agendas de esta sucursal
			//------------------------------------------------------------
			$Agenda = new Agenda();
			$xAgendas = $Agenda->find('all',array(
									'conditions'=>array(
										'Agenda.sucursal_id' => $sucursal_id,
										'NOT' => array ('Agenda.alcance' => 'pri'),
										'NOT' => array ('Agenda.staterecord_id' => array('2','3') )
									)
								));
			$Agendas = array();
			foreach ($xAgendas as $value) {
				$Agendas[$value['Agenda']['id']] = $value['Agenda']['id'];
			}

			$condicion_profesional = array(
										'Turn.client_id' => $client_id,
										'Turn.fecha BETWEEN ? AND ?' => array($tz_fecha_inicio,$tz_fecha_fin ),
										'Turn.agenda_id' => $Agendas,
										'NOT' => array ('Turn.staterecord_id' => array('2','3'))
									);



		} else {

			$condicion_profesional = array(
										'Turn.client_id' => $client_id,
										'Turn.agenda_id' => $agenda_id,
										'Turn.fecha BETWEEN ? AND ?' => array($tz_fecha_inicio,$tz_fecha_fin ),
										'NOT' => array ('Turn.staterecord_id' => array('2','3'))
									);

		}

		$this->unbindModel( array('belongsTo' => array('Client', 'User','Staterecord','Stateturn') ) );		

		$lst_turnos = $this->find('all', array(
						'conditions' => $condicion_profesional,
						'order' => array('Turn.fecha')
					));

		if($lst_turnos){

			$PeopleProduct = new PeopleProduct();
			
					
			//----------------------------------------------------
			//              Se le asigno el valor de la consulta??
			//----------------------------------------------------
			foreach($lst_turnos as $clave=>$valor){
				$lst_turnos[$clave]['Turn']['valor_consulta']=0;

				if($valor['Turn']['person_id']>0){
					$fecha     = substr($valor['Turn']['fecha'],0,10);
					$doctor_id = $valor['Turn']['doctor_id'];
					$person_id = $valor['Turn']['person_id'];
					
					$sqlValorConsulta = array(
										'PeopleProduct.client_id' => $client_id,
										'PeopleProduct.person_id' => $person_id,
										'PeopleProduct.fecha like' => "$fecha%"
									);

					$pago = $PeopleProduct->find('first',$sqlValorConsulta);

					if(count($pago)>0){
						$lst_turnos[$clave]['Turn']['valor_consulta']=1;
					}
				}

				//--------------- Convierte las fechas/horas al timezone del cliente
				if(empty($valor['Turn']['hora_llegada']) OR $valor['Turn']['hora_llegada'] == "0000-00-00 00:00:00"){
					$lst_turnos[$clave]['Turn']['hora_de_llegada'] = '--';	
				} else {
					$hora_aux     = new DateTime(date('Y-m-d H:i', strtotime($valor['Turn']['hora_llegada'])));
					$offset       = $client_tz->getOffset($hora_aux);
					$hora_llegada = date('H:i', $hora_aux->format('U') + $offset);
					$lst_turnos[$clave]['Turn']['hora_de_llegada'] = $hora_llegada;
				}

				$hora_aux   = new DateTime(date('Y-m-d H:i', strtotime($valor['Turn']['fecha'])));
				$offset     = $client_tz->getOffset($hora_aux);
				$hora_turno = date('H:i', $hora_aux->format('U') + $offset);
				$lst_turnos[$clave]['Turn']['hora_turno'] = $hora_turno;


				if($valor['Agenda']['specialty_id']>0){
					$lst_turnos[$clave]['Turn']['nombre_agenda'] = $valor['Agenda']['nombre'];					
				} else {
					$lst_turnos[$clave]['Turn']['nombre_agenda'] = $valor['Doctor']['tratamiento'].'.'.$valor['Doctor']['lastname'].', '.$valor['Doctor']['name'];
				}


			} // endforeach
		}

		return $lst_turnos;
	}




}
?>